// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package config

import (
	"os"

	"gitcode.com/openseaotter/so_agent/utils"
	"gopkg.in/yaml.v3"
)

type WatchConfig struct {
	WatchId    string `yaml:"watchId"`
	ServerAddr string `yaml:"serverAddr"`
	Secret     string `yaml:"secret"`
	ScriptFile string `yaml:"scriptFile"`
}

type AgentConfig struct {
	MaxExecSecond uint32        `ymal:"maxEcexSecond"`
	WatchCfgList  []WatchConfig `yaml:"watchCfgList"`
}

func ReadAgentConfig() (*AgentConfig, error) {
	data, err := os.ReadFile(utils.CONFIG_FILE_PATH)
	if err != nil {
		return nil, err
	}
	cfg := &AgentConfig{}
	err = yaml.Unmarshal(data, cfg)
	if err != nil {
		return nil, err
	}
	if cfg.WatchCfgList == nil {
		cfg.WatchCfgList = []WatchConfig{}
	}
	return cfg, nil
}

func WriteAgentConfig(cfg *AgentConfig) error {
	if cfg.WatchCfgList == nil {
		cfg.WatchCfgList = []WatchConfig{}
	}
	data, err := yaml.Marshal(cfg)
	if err != nil {
		return err
	}
	os.MkdirAll(utils.CONFIG_DIR_PATH, 0755) //skip error check
	err = os.WriteFile(utils.CONFIG_FILE_PATH, data, 0644)
	if err != nil {
		return err
	}
	return nil
}
